var gulp = require('gulp'),
    contentIncluder = require('gulp-content-includer'),
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    autoPrefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create(),
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    runSequence = require('gulp-sequence'),
    cache = require('gulp-cache'),

    P = require('./config.js').pathes,
    mergeSass = require('./merge-sass.js')

/*include html*/
gulp.task('includeHtml', function () {
    return gulp.src(P.src + '/*.html')
        .pipe(rename({
            dirname: ''
        }))
        .pipe(contentIncluder({
            includerReg: /<!\-\-include\s+"([^"]+)"\-\->/g
        }))
        .pipe(gulp.dest(P.dev + '/'))
})

/*编译sass文件*/
gulp.task('sass', function () {
    mergeSass()
    return gulp.src([P.src + '/css/*.scss', P.src + '/common/common.scss'])
        .pipe(rename({
            dirname: ''
        }))
        .pipe(sass({
            outputStyle: 'expanded'
        }).on('error', sass.logError))
        .pipe(autoPrefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4']
        }))
        .pipe(gulp.dest(P.dev + '/css'))
})

/*合并js*/
gulp.task('concatJs', function () {
    return gulp.src([P.src + '/common/*.js', P.src + '/modules/*/*.js'])
        .pipe(rename({
            dirname: ''
        }))
        .pipe(concat('common.js'))
        .pipe(gulp.dest(P.dev + '/js'))
})

/*复制*/
gulp.task('copy:js', function () {
    return gulp.src(P.src + '/js/*.js')
        .pipe(rename({
            dirname: ''
        }))
        .pipe(gulp.dest(P.dev + '/js'))
})


gulp.task('copy:img', function () {
    return gulp.src([P.src + '/images/*', P.src + '/css/*', P.src + '/fonts/**'], {
            base: P.src
        })
        .pipe(gulp.dest(P.dev))
})

gulp.task('clean', function () {
    cache.clearAll()
    return gulp.src([P.dev, P.build])
        .pipe(clean())
})

module.exports = {
    start: function () {
        gulp.task('dev', runSequence('clean', ['includeHtml', 'sass', 'concatJs', 'copy:js', 'copy:img']))
    }
}